﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Bookkeeping.Core.Persistence;
using NHibernate;

namespace Bookkeeping.Persistence.Repositories
{
    public class Repository<TEntity, TId> : IDisposable, IRepository<TEntity, TId>
        where TEntity : class
    {
        private bool hasCreatedSession;
        private bool isDisposed;

        protected ISession Session { get; set; }

        public Repository()
        {
            Session = SessionFactorySingleton.OpenSession();
            hasCreatedSession = true;
        }

        public Repository(ISession session)
        {
            Session = session;
        }

        public void Dispose()
        {
            if (!isDisposed && hasCreatedSession)
            {
                Session.Dispose();
                isDisposed = true;
            }
        }

        public TEntity Get(TId id)
        {
            return Session.Get<TEntity>(id);
        }

        public IList<TEntity> GetAll()
        {
            return Session.CreateCriteria(typeof(TEntity)).List<TEntity>();
        }

        public void Delete(TEntity entity)
        {
            using (ITransaction transaction = Session.BeginTransaction())
            {
                Session.Delete(entity);

                transaction.Commit();
            }
        }

        public void Delete(TId id)
        {
            using (ITransaction transaction = Session.BeginTransaction())
            {
                var entity = Get(id);
                Session.Delete(entity);

                transaction.Commit();
            }
        }

        public void Delete(IEnumerable<TEntity> entities)
        {
            using (ITransaction transaction = Session.BeginTransaction())
            {
                foreach (var entity in entities)
                    Session.Delete(entity);

                transaction.Commit();
            }
        }

        public void Insert(TEntity entity)
        {
            using (ITransaction transaction = Session.BeginTransaction())
            {
                Session.Save(entity);

                transaction.Commit();
            }
        }

        public void SaveChanges()
        {
            Session.Flush();
        }

        public void Load(object toInitialize)
        {
            NHibernateUtil.Initialize(toInitialize);
        }

        public void AttachUnchanged(TEntity entity)
        {
            Session.Lock(entity, LockMode.None);
        }

        public void AttachChanged(TEntity entity)
        {
            Session.Update(entity);
        }
    }
}
